package com.example.speeddating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.speeddating.constants.Constants;
import com.example.speeddating.entity.EmailCode;
import com.example.speeddating.entity.User;
import com.example.speeddating.exception.CommonException;
import com.example.speeddating.mapper.EmailCodeMapper;
import com.example.speeddating.mapper.UserMapper;
import com.example.speeddating.service.EmailCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.speeddating.tool.StringTools;
//import jakarta.annotation.Resource;
//import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 *
 * @author tina
 * @since 2023-07-20 10:56:04
 */
@Service
public class EmailCodeServiceImpl extends ServiceImpl<EmailCodeMapper, EmailCode> implements EmailCodeService {

    @Autowired
    private EmailCodeMapper emailCodeMapper;

    @Autowired
    private UserMapper userMapper;

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sendUser;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendEmailCode(String email, Integer type) {
        if (type == Constants.ZERO) {
            // 注册
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("email", email);
            if (userMapper.selectOne(queryWrapper) != null) {
                throw new CommonException("邮箱已存在");
            }
        }

        String code = StringTools.getRandomString(Constants.LENGTH_5);
        sendEmail(email, code);
        emailCodeMapper.disableEmailCode(email); //让之前的验证码都失效
        EmailCode emailCode = new EmailCode();
        emailCode.setCode(code);
        emailCode.setEmail(email);
        emailCode.setStatus(Constants.ZERO);
        emailCodeMapper.insert(emailCode);
    }

    @Override
    public void checkCode(String email, String code) {
        EmailCode emailCode = emailCodeMapper.checkCode(email, code);
        if (emailCode==null) {
            throw new CommonException("邮箱验证码不正确");
        }
        if (System.currentTimeMillis()-emailCode.getCreateTime().getTime()>=1000*60*Constants.LENGTH_15){
            throw new CommonException("验证码已失效");
        }
        emailCodeMapper.disableEmailCode(email);
    }

    private void sendEmail(String toEmail, String code) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //邮件发送人
            helper.setFrom(sendUser);
            //邮件收件人
            helper.setTo(toEmail);
            //邮件主题
            helper.setSubject("注册Soulmate邮箱验证码");
            helper.setText("邮箱验证码为"+code);
            helper.setSentDate(new Date());
            javaMailSender.send(message);
        } catch (Exception e) {
            log.error("发送邮件失败");
            throw new CommonException("邮件发送失败");
        }

    }
}
